package com.mingmen.supplier.activity;


import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.lzy.imagepicker.ImagePicker;
import com.mingmen.supplier.R;
import com.mingmen.supplier.adapter.CommodityAdapter;
import com.mingmen.supplier.adapter.CommodityAllAdapter;
import com.mingmen.supplier.adapter.CommodityLabelAdapter;
import com.mingmen.supplier.adapter.CommodityManagerAdapter;
import com.mingmen.supplier.adapter.CommodityRightAdapter;
import com.mingmen.supplier.base.BaseBean;
import com.mingmen.supplier.defineview.ClearEditText;
import com.mingmen.supplier.http.callback.StringCallback;
import com.mingmen.supplier.httpconfig.HttpResponse;
import com.mingmen.supplier.immersionbar.ImmersionBar;
import com.mingmen.supplier.label.bean.LabelTestBean;
import com.mingmen.supplier.label.recycler.OnItemClickListener;
import com.mingmen.supplier.model.CommodityAllModel;
import com.mingmen.supplier.model.CommodityBasicModel;
import com.mingmen.supplier.model.CommodityListModel;
import com.mingmen.supplier.model.CommodityRightModel;
import com.mingmen.supplier.model.CommodityShopModel;
import com.mingmen.supplier.model.EventBean;
import com.mingmen.supplier.model.ShopListModel;
import com.mingmen.supplier.model.TestBean;
import com.mingmen.supplier.popwindow.PopupWindowCompat;
import com.mingmen.supplier.refresh.ClassicsFooter;
import com.mingmen.supplier.refresh.ClassicsHeader;
import com.mingmen.supplier.util.GsonUtil;
import com.mingmen.supplier.util.MyStringUtils;
import com.mingmen.supplier.util.SharePreferenceUtil;
import com.mingmen.supplier.util.ToolList;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;
import okhttp3.Call;
import okhttp3.Response;

public class CommodityShopManagerActivity extends AppCompatActivity implements CommodityManagerAdapter.OnItemClickListener {

    //返回按钮
    @BindView(R.id.text_return)
    TextView textReturn;

    private ImagePicker imagePicker;

    @BindView(R.id.btn_login)
    Button btn_login;

    private int resurtResurant = 100;
    @BindView(R.id.recycle_shopo)
    RecyclerView mRecyclerView;

    CommodityManagerAdapter commodityAdapter;
    LinearLayoutManager linearLayoutManager;
    @BindView(R.id.view_dishline)
    View view_dishline;

    private List<CommodityShopModel.DataBean> mListData = new ArrayList<>();
    @BindView(R.id.btn_addcommity)
    Button btn_addcommity;
    String token;
    List<String> commodityIds = new ArrayList<>();
    @BindView(R.id.text_already)
    TextView text_already;
    @BindView(R.id.check_selectAll)
    CheckBox check_selectAll;
    @BindView(R.id.linear_return)
    LinearLayout linear_return;
    @BindView(R.id.refreshLayout)
    RefreshLayout refreshLayout;
    int pageNumber = 1;
    int totalPage;
    @BindView(R.id.layout_alldata)
    LinearLayout layout_alldata;
    @BindView(R.id.layout_nodata)
    LinearLayout layout_nodata;

    int flag = 0;
    @BindView(R.id.main_search)
    ClearEditText main_search;
    @BindView(R.id.layout_pinlei)
    LinearLayout layout_pinlei;
    private List<CommodityAllModel.DataBean> mLabelList = new ArrayList<>();
    @BindView(R.id.text_allCategory)
    TextView text_allCategory;
    @BindView(R.id.img_jingying)
    ImageView img_jingying;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_commoditymanager);
        ButterKnife.bind(this);
        ImmersionBar.with(this)
                .statusBarDarkFont(true, 0.2f)
                .init();
        EventBus.getDefault().register(this);
        token = (String) SharePreferenceUtil.get(this, "token", "");
        linearLayoutManager = new LinearLayoutManager(this);

        mRecyclerView.setLayoutManager(linearLayoutManager);
        commodityAdapter = new CommodityManagerAdapter(this, mListData);
        mRecyclerView.setAdapter(commodityAdapter);
        commodityAdapter.setOnItemClickListener(this);
        getData(token, "", "", pageNumber);
        popWindowCreate();
        refreshLayout.setRefreshHeader(new ClassicsHeader(CommodityShopManagerActivity.this));
        refreshLayout.setRefreshFooter(new ClassicsFooter(CommodityShopManagerActivity.this));

        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                if (mListData.size() > 0) {
                    mListData.clear();
                }
                flag = 0;
                check_selectAll.setChecked(false);
                pageNumber = 1;

//                refreshlayout.finishRefresh(2000/*,false*/);//传入false表示刷新失败
                getData(token, "", "", pageNumber);
            }
        });

        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                if (pageNumber >= totalPage) {
                    Toast.makeText(CommodityShopManagerActivity.this, "已到最后一页", Toast.LENGTH_SHORT).show();
                    refreshlayout.finishLoadMore(false);//传入false表示加载失败
                } else {
                    pageNumber++;

//                    getData(token, "", "", pageNumber);
                    HttpResponse.getAllCommodity(token, "", "", pageNumber, new StringCallback(CommodityShopManagerActivity.this) {
                        @Override
                        public void onSuccess(String s, Call call, Response response) {

                            CommodityShopModel commodityShopModel = new CommodityShopModel();
                            commodityShopModel = GsonUtil.GsonToBean(s, CommodityShopModel.class);
                            mListData.addAll(commodityShopModel.getData());
                            if (flag == 1) {

                                for (int i = 0; i < mListData.size(); i++) {

                                    mListData.get(i).setChecked(true);
                                    commodityIds.add(mListData.get(i).getCommodityId());
                                    commodityAdapter.notifyDataSetChanged();

                                }

                            } else {
                                for (int i = 0; i < mListData.size(); i++) {

                                    mListData.get(i).setChecked(false);
                                    commodityIds.clear();
                                    commodityAdapter.notifyDataSetChanged();

                                }
                            }


                            totalPage = commodityShopModel.getTotalPage();
                            if (mListData.size() == 0) {
                                layout_alldata.setVisibility(View.GONE);
                                layout_nodata.setVisibility(View.VISIBLE);
                            } else {
                                layout_alldata.setVisibility(View.VISIBLE);
                                layout_nodata.setVisibility(View.GONE);
                            }
                            commodityAdapter.setDataList(mListData);
                        }

                        @Override
                        public void onAfter(String s, Exception e) {
                            super.onAfter(s, e);
                            refreshLayout.finishRefresh(100/*,false*/);//传入false表示刷新失败
                            refreshLayout.finishLoadMore(100/*,false*/);//传入false表示加载失败
                        }
                    });
                    refreshlayout.finishLoadMore(100/*,false*/);//传入false表示加载失败
                }


            }
        });


        check_selectAll.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    if (check_selectAll.isChecked()) {
                        flag = 1;
                        for (int i = 0; i < mListData.size(); i++) {

                            mListData.get(i).setChecked(true);
                            commodityIds.add(mListData.get(i).getCommodityId());
                            commodityAdapter.notifyDataSetChanged();

                        }
                        ToolList.removeDuplicateWithOrder(mListData);
                    }
                } else {
                    flag = 0;
                    for (int i = 0; i < mListData.size(); i++) {
                        mListData.get(i).setChecked(false);
                        commodityIds.clear();
                        commodityAdapter.notifyDataSetChanged();
                    }
                }
            }
        });
        commodityAdapter.setOnItemClickListener(new CommodityManagerAdapter.OnItemClickListener() {
            @Override
            public void onItemClickListener(View view, int pos, List<CommodityShopModel.DataBean> myLiveList) {
                Intent intent;
                switch (view.getId()) {
                    case R.id.checkItem:
                        for (CommodityShopModel.DataBean cart : mListData) {
                            if (cart.isChecked()) {   //是否勾上去了
                                Log.d("勾选上了", "勾选上了");
                                commodityIds.add(myLiveList.get(pos).getCommodityId());
                                ToolList.removeDuplicateWithOrder(commodityIds);
                                Log.d("applyListapplyListapplyList", commodityIds.toString());
                            } else {
                                Log.d("取消勾选", "取消勾选");
                                if (commodityIds.size() > 0) {
                                    for (int i = 0; i < commodityIds.size(); i++) {
                                        if (commodityIds.get(i).contains(cart.getCommodityId())) {
                                            commodityIds.remove(i);
                                        }
                                    }
                                }
                                ToolList.removeDuplicateWithOrder(commodityIds);
                            }
                        }
                        break;
                    case R.id.text_manager:
                        if (myLiveList.get(pos).getFlag().equals("0")) {
//                            addShop(token, myLiveList.get(pos).getCommodityId());

//                            String commodityIds_Send = MyStringUtils.returnStringBuffer(commodityIds);
//                    addShop(token, commodityIds_Send);
                            intent = new Intent(CommodityShopManagerActivity.this, CommodityBasicActivity.class);
                            intent.putExtra("commodityIds_Send", myLiveList.get(pos).getCommodityId());
//                    startActivity(intent);
                            startActivityForResult(intent, resurtResurant);
                        } else {

                            HttpResponse.removeSupplierCommodity(token, myLiveList.get(pos).getCommodityId(), new StringCallback(CommodityShopManagerActivity.this) {
                                @Override
                                public void onSuccess(String s, Call call, Response response) {
                                    BaseBean baseBean = new BaseBean();
                                    baseBean = GsonUtil.GsonToBean(s, BaseBean.class);
                                    if (baseBean.getCode() == 0) {
                                        mListData.clear();
                                        EventBus.getDefault().post(11);
                                    }
                                    Toast.makeText(CommodityShopManagerActivity.this, baseBean.getMessage() + "", Toast.LENGTH_SHORT).show();

                                    getData(token, "", "", 1);


                                }
                            });

                            /*  String commodityIds_Send = MyStringUtils.returnStringBuffer(commodityIds);
                            if (TextUtils.isEmpty(commodityIds.toString())) {
                                Toast.makeText(CommodityShopManagerActivity.this, "请选择要下架的商品", Toast.LENGTH_SHORT).show();
                            } else if (commodityIds.size() == 0) {
                                Toast.makeText(CommodityShopManagerActivity.this, "请选择要下架的商品", Toast.LENGTH_SHORT).show();
                            }else {
                                HttpResponse.removeSupplierCommodity(token, commodityIds_Send, new StringCallback(CommodityShopManagerActivity.this) {
                                    @Override
                                    public void onSuccess(String s, Call call, Response response) {
                                        BaseBean baseBean=new BaseBean();
                                        baseBean=GsonUtil.GsonToBean(s,BaseBean.class);
                                        Toast.makeText(CommodityShopManagerActivity.this, baseBean.getMessage()+"", Toast.LENGTH_SHORT).show();
                                        getData();
                                    }
                                });
                            }*/


                        }
                        break;
                }

            }

        });

        main_search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(s.toString())) {
                    getData(token, "", "", pageNumber);
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(main_search.getWindowToken(), 0);
                } else if (s.toString().length() < 1) {
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(main_search.getWindowToken(), 0);
                } else {

                }

            }
        });
        main_search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                getData(token, "", main_search.getText().toString(), pageNumber);

                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);


                return false;
            }
        });


    }

    public void getData(String token, String categoryId, String keyword, int pageNumber) {
        HttpResponse.getAllCommodity(token, categoryId, keyword, pageNumber, new StringCallback(this) {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                if (mListData.size() > 0) {
                    mListData.clear();
                }
                CommodityShopModel commodityShopModel = new CommodityShopModel();
                commodityShopModel = GsonUtil.GsonToBean(s, CommodityShopModel.class);
                mListData.addAll(commodityShopModel.getData());
                if (flag == 1) {

                    for (int i = 0; i < mListData.size(); i++) {

                        mListData.get(i).setChecked(true);
                        commodityIds.add(mListData.get(i).getCommodityId());
                        commodityAdapter.notifyDataSetChanged();

                    }

                } else {
                    for (int i = 0; i < mListData.size(); i++) {

                        mListData.get(i).setChecked(false);
                        commodityIds.clear();
                        commodityAdapter.notifyDataSetChanged();

                    }
                }


                totalPage = commodityShopModel.getTotalPage();
                if (mListData.size() == 0) {
                    layout_alldata.setVisibility(View.GONE);
                    layout_nodata.setVisibility(View.VISIBLE);
                } else {
                    layout_alldata.setVisibility(View.VISIBLE);
                    layout_nodata.setVisibility(View.GONE);
                }
                commodityAdapter.setDataList(mListData);
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(main_search.getWindowToken(), 0);
            }

            @Override
            public void onAfter(String s, Exception e) {
                super.onAfter(s, e);
                refreshLayout.finishRefresh(100/*,false*/);//传入false表示刷新失败
                refreshLayout.finishLoadMore(100/*,false*/);//传入false表示加载失败
            }
        });
    }

    @OnClick({R.id.text_return, R.id.btn_login, R.id.btn_addcommity, R.id.text_already, R.id.linear_return, R.id.layout_pinlei})
    public void onViewClicked(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.text_return:
                finish();
                break;
            case R.id.btn_login:
                break;
            case R.id.btn_addcommity:
                startActivity(new Intent(CommodityShopManagerActivity.this, CreateCommodityActivity.class));
                break;
            case R.id.linear_return:
                finish();
                break;
            case R.id.text_already:

                if (TextUtils.isEmpty(commodityIds.toString())) {
                    Toast.makeText(this, "请选择要增加的商品", Toast.LENGTH_SHORT).show();
                } else if (commodityIds.size() == 0) {
                    Toast.makeText(this, "请选择要增加的商品", Toast.LENGTH_SHORT).show();
                } else {
                    Log.d("CommodityShopManagerActivity", commodityIds.toString());
                    String commodityIds_Send = MyStringUtils.returnStringBuffer(commodityIds);
//                    addShop(token, commodityIds_Send);
                    intent = new Intent(CommodityShopManagerActivity.this, CommodityBasicActivity.class);
                    intent.putExtra("commodityIds_Send", commodityIds_Send);
//                    startActivity(intent);
                    startActivityForResult(intent, resurtResurant);
//                    startActivity(new Intent(CommodityShopManagerActivity.this, CommodityBasicActivity.class));

                }
//                setCommodityFromLibrary
                break;
            case R.id.layout_pinlei:

                img_jingying.setRotation(360);
                img_jingying.setImageResource(R.mipmap.arrowblue_bottom);

                popupWindow.showAsDropDown(layout_pinlei);
                break;
        }
    }

    public void addShop(String token, String commodityIds) {

        HttpResponse.setCommodityFromLibrary(token, commodityIds, new StringCallback(this) {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                Log.d("setCommodityFromLibrary", s);
                BaseBean baseBean = new BaseBean();
                baseBean = GsonUtil.GsonToBean(s, BaseBean.class);
                Toast.makeText(CommodityShopManagerActivity.this, baseBean.getMessage() + "", Toast.LENGTH_SHORT).show();
                if (baseBean.getCode() == 0) {
                    EventBus.getDefault().post(11);
                    getData(token, "", "", 1);
                }
            }
        });
    }

    @Override
    public void onItemClickListener(View view, int pos, List<CommodityShopModel.DataBean> myLiveList) {

    }

    public void onEventMainThread(Integer integer) {


    }

    CommodityAllAdapter commodityLabelAdapter;
    PopupWindowCompat popupWindow;

    public void popWindowCreate() {
//        CommodityFragment
        popupWindow = new PopupWindowCompat(this);
        View contentView = LayoutInflater.from(this).inflate(R.layout.pop_right, null);
        popupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        popupWindow.setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
        popupWindow.setContentView(contentView);
        popupWindow.setOutsideTouchable(false);
        popupWindow.setFocusable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        TextView textView = contentView.findViewById(R.id.tv_kdd);
        textView.setText("");
        LinearLayout layout_content = contentView.findViewById(R.id.layout_content);
        layout_content.getBackground().setAlpha(180);
        RecyclerView recyclerView = contentView.findViewById(R.id.recycler_view);

        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        DividerItemDecoration divider = new DividerItemDecoration(CommodityShopManagerActivity.this, DividerItemDecoration.VERTICAL);

        divider.setDrawable(ContextCompat.getDrawable(CommodityShopManagerActivity.this, R.drawable.custom_divider));
//        recyclerView.addItemDecoration(divider);
        commodityLabelAdapter = new CommodityAllAdapter(CommodityShopManagerActivity.this, mLabelList);
        recyclerView.setAdapter(commodityLabelAdapter);
        commodityLabelAdapter.setOnItemClickListener(new CommodityAllAdapter.OnItemClickListener() {
            @Override
            public void OnItemClick(View view, int position, List<CommodityAllModel.DataBean> mListData) {
                commodityLabelAdapter.setCheckedPosition(position);
                text_allCategory.setText(mListData.get(position).getCategoryName());
                getData(token, mListData.get(position).getCategoryId(), "", pageNumber);
                img_jingying.setImageResource(R.mipmap.arrowblue_bottom);

                img_jingying.setRotation(180);
                popupWindow.dismiss();
            }
        });
        HttpResponse.getCategoryList(token, "0", "0", new StringCallback(this) {
            @Override
            public void onSuccess(String s, Call call, Response response) {

                Log.d("getCategoryList", s);

                BaseBean baseBean = new BaseBean();
                baseBean = GsonUtil.GsonToBean(s, BaseBean.class);
                if (baseBean.getCode() == 0) {
                    CommodityAllModel commodityAllModel = new CommodityAllModel();
                    commodityAllModel = GsonUtil.GsonToBean(s, CommodityAllModel.class);

                    List<CommodityAllModel.DataBean.ChildrenBean> childrenBeans = new ArrayList<>();
                    CommodityAllModel.DataBean dataBean1 = new CommodityAllModel.DataBean();
                    dataBean1.setCategoryName("全部分类");
                    dataBean1.setParentId("666");
                    dataBean1.setCategoryId("0");
                    dataBean1.setHavaChildren(0);
                    dataBean1.setChildren(childrenBeans);
                    mLabelList.add(dataBean1);
                    mLabelList.addAll(commodityAllModel.getData());
                    commodityLabelAdapter.update(mLabelList);

                } else {
                    startActivity(new Intent(CommodityShopManagerActivity.this, LoginActivity.class));
                    Toast.makeText(CommodityShopManagerActivity.this, baseBean.getMessage() + "", Toast.LENGTH_SHORT).show();
                    finish();

                }


            }
        });
    }

    String jdata;
    List<CommodityListModel.SendListBean> commoditiesBeanList = new ArrayList<>();

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == resurtResurant) {
            jdata = data.getStringExtra("jdata");
            Log.d("jdatajdata", jdata);
//            JSONObject jsonObject1 =JSONObject.parseObject(String)


            CommodityListModel commodityListModel = new CommodityListModel();
            commodityListModel = GsonUtil.GsonToBean(jdata, CommodityListModel.class);
            commoditiesBeanList = commodityListModel.getSendList();
            JSONObject jsonObject = new JSONObject();
            List<String> jdatas = new ArrayList<>();
            for (int i = 0; i < commoditiesBeanList.size(); i++) {
                try {
                    jsonObject.put("commodityId", commoditiesBeanList.get(i).getCommodityId());
                    jsonObject.put("price", commoditiesBeanList.get(i).getPrice());
                    jsonObject.put("amount", commoditiesBeanList.get(i).getAmount());
                    jdatas.add(jsonObject.toString());
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
            String jdata = MyStringUtils.returnStringBuffer(jdatas);
            addShop(token, jdata);
/*
//            Log.d("jdatajJsonObject", jsonObject1.toString());
            CommodityBasicModel commodityBasicModel = new CommodityBasicModel();
            commodityBasicModel = GsonUtil.GsonToBean(jdata, CommodityBasicModel.class);
//            commodityBasicModel = GsonUtil.GsonToBean(jsonObject1.toString(), CommodityBasicModel.class);
            commoditiesBeanList = commodityBasicModel.getData();
            JSONObject jsonObject = new JSONObject();
            List<String> jdatas = new ArrayList<>();
            for (int i = 0; i < commoditiesBeanList.size(); i++) {
                try {
                    jsonObject.put("commodityId", commoditiesBeanList.get(i).getId());
                    jsonObject.put("price", commoditiesBeanList.get(i).getPrice());
                    jsonObject.put("amount", commoditiesBeanList.get(i).getAmount());
                    jdatas.add(jsonObject.toString());
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
            String jdata = MyStringUtils.returnStringBuffer(jdatas);
            addShop(token, jdata);*/
        }

    }
}




